﻿using mozhi.smarterp.Finance.Files.Repository;
using System;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Services;
using Volo.Abp.Guids;

namespace mozhi.smarterp.Finance.Files.Services
{
    public class AttachmentManager : DomainService
    {
        private IFileRepository _fileRepository;
        private IGuidGenerator _guidGenerator;
        private IAttachmentRepository _attachmentRepository;
        public AttachmentManager(IFileRepository fileManager , IAttachmentRepository attachmentRepository , IGuidGenerator guidGenerator)
        {
            _fileRepository = fileManager;
            _attachmentRepository = attachmentRepository;
            _guidGenerator = guidGenerator;
        }

        public async Task<Attachment> CreateAsync(string moduleCode , Guid ownerId , Guid remoteFileId)
        {
            var file = await _fileRepository.FindAsync(remoteFileId);

            if (file == null)
                throw new BusinessException("100000", $"远程文件Id:{remoteFileId}不存在");

            var attchment = new Attachment(_guidGenerator.Create(), ownerId, moduleCode, file.FileName, file.FileExtension, file.ContentType , file.Id);

            attchment = await _attachmentRepository.InsertAsync(attchment);

            return attchment;
        }

        public async Task DeleteAsync(Guid id)
        {
            var attachment = await _attachmentRepository.GetAsync(id);

            if (attachment == null)
                return;

            await _attachmentRepository.DeleteAsync(attachment);
        }
    }
}
